<?php
namespace Home\Controller;
use Think\Controller;
use Think\Verify;
use Think\Model;
use Think\Db;

class LoginController extends Controller
{
	public function index()
	{

		$this->assign("CurrentPage",'home');
        $this->display();
	}

	public function login(){
        ini_set("session.cookie_httponly", 1);
		//

		//\Think\Log::write('logsql22'.json_encode($_REQUEST));
		if(IS_POST){
            $key="luyinxitong";
		    //$captcha = $_REQUEST['captcha'];
		    $loginName = $_REQUEST['uname'];
            $lt = S($loginName);
            if($lt >= 5){
                $returnData['msg'] = "操作过于频繁，请5分钟后再试";
                $returnData['code'] =0;
                $this->ajaxReturn($returnData);
            }
		    $where = array();
			//$this->check_verify($captcha)==true
		   if(1){
			 //\Think\Log::write('log222222222'.json_encode($_REQUEST));
                $userModel = M("sys_accountinfo");

				//$where['V_AccountName'] = base64_decode($_REQUEST['uname']);
				$where['V_AccountName'] = $_REQUEST['uname'];
				$upwd=isset($_POST["IPASSWORD"])?$_POST["IPASSWORD"]:"";

                //$where['V_Password'] = md5(base64_decode($upwd).$key);
				$where['V_Password'] = $upwd;


				//检测是否从monitor登录，如果有则从HID_INAME接收用户名
				if(isset($_REQUEST["INAME"]) && $_REQUEST["INAME"] !=''){
				//\Think\Log::write('log333'.json_encode($_REQUEST));
					if(trim($_REQUEST["INAME"]) !="" && !empty($_REQUEST["INAME"]) && $_REQUEST["INAME"] != null){
						$where['V_AccountName'] =$_REQUEST["INAME"];
					}
				}

				$where['N_Status'] = array('neq',0);
				if(!$userModel->find()){
                    $returnData['msg'] = "数据库连接失败";
                    $returnData['code'] =0;
                    $this->ajaxReturn($returnData);
                }
				$rs  = $userModel->where($where)->find();
				// $sql = M()->getLastSql(); echo $sql;exit;
				//\Think\Log::write('logsql'.$sql);
				if($rs) {
				    session("uAccount",$rs['v_accountid']);//用户ID
				    session("uName",$rs['v_accountname']);//用户账号
				    session("uRights",$rs['n_afairtype']);//用户权限
				    session("uLogTime",date("Y-m-d H:i:s"));//登录时间
				    session("uPrivilege",$rs['n_privilege']);//有权设备
				    session("uLogIP",get_ip());//登录地址
				    session("V_Ext",$rs['v_ext']);//有权分机
				    session("V_SID",$rs['v_sid']);//有权工作站
				    session("admininfo",$rs);
                    S($loginName,0);
				    $returnData['url']                   = "/home/record/recordList";
				    $returnData['msg'] = "登录成功,正在跳转...";
				    $returnData['code'] =1;
					addSysLog("用户:".$rs['v_accountname']."通过IP".get_ip()."登录系统");

				}
				else{
				    $returnData['msg'] = "账号或密码错误";
				    $returnData['code'] =0;
				}
			}
			else
			{
                $value = S($loginName)+1;
                S($loginName,$value,300);
			    $returnData['msg'] = "验证码错误";
			    $returnData['code'] =0;
			}
			//$returnData = (object) $returnData;
			$this->ajaxReturn($returnData);
		}
	}

	public function thirdLogin(){
        if(IS_POST){
            $userModel = M("sys_accountinfo");
            $uname = isset($_POST["name"])?$_POST["name"]:"";
            $upwd=isset($_POST["password"])?$_POST["password"]:"";
            if(empty($uname) || empty($upwd)){
                $returnData['msg'] = "name或password参数不能为空";
                $returnData['code'] =1;
                $this->ajaxReturn($returnData);
            }
            $where['V_AccountName'] =  $uname;
            $where['V_Password'] = $upwd;
            $where['N_Status'] = array('neq',0);
            $rs  = $userModel->where($where)->find();
            if($rs) {
                session("uAccount",$rs['v_accountid']);//用户ID
                session("uName",$rs['v_accountname']);//用户账号
                session("uRights",$rs['n_afairtype']);//用户权限
                session("uLogTime",date("Y-m-d H:i:s"));//登录时间
                session("uPrivilege",$rs['n_privilege']);//有权设备
                session("uLogIP",get_ip());//登录地址
                session("V_Ext",$rs['v_ext']);//有权分机
                session("V_SID",$rs['v_sid']);//有权工作站
                session("admininfo",$rs);

                $returnData['url']                   = host()."home/record/thirdRecordList";
                $returnData['msg'] = "登录成功";
                $returnData['code'] =0;
                addSysLog("用户:".$rs['v_accountname']."通过IP".get_ip()."登录系统");

            }
            else{
                $returnData['msg'] = "账号或密码错误";
                $returnData['code'] =1;
            }

        }else{
            $returnData['msg'] = "请求方式错误,请用POST请求";
            $returnData['code'] =1;
        }
        $this->ajaxReturn($returnData);
    }

    public function indexInfo(){
        header('Access-Control-Allow-Origin: *');
        $time = "--";
        $recNum = 0;
        $bakrecNum = 0;
        $diskSize = 0;
        $diskUsed = 0;
        $diskUsePercent = 0;
        $fpath = '';
        $rec = M("sys_diskspaceinfo")->order('N_StationId asc')->find();
        if($rec){
            $diskSize = round($rec['n_totalspace']/1000,2);
            $diskAvail = round($rec['n_freespace']/1000,2);
            $diskUsed = round($diskSize - $diskAvail,2);
            $diskUsePercent = round($diskUsed/$diskSize,2)*100;
            $fpath = $rec['v_rcdiskpath4vpath'];
        }
        //当前录音磁盘使用情况
        $field="v_recorddiskpath,v_rcdiskpath4vpath";
        $rsUsing = M('sys_diskspaceinfo')->join("tab_rec_recorddiskcfg a")->field($field)->where("V_RecordDiskPath  like CONCAT(V_DiskVolumeName,'%')")->select();
        $curDisk = substr($rsUsing[0]['v_recorddiskpath'],0,2);
        if($curDisk){
            $diskinfo = M('sys_diskspaceinfo')->where("V_DiskVolumeName = '{$curDisk}'")->find();
            $diskSize = round($diskinfo["n_totalspace"]/1000,2);
            $diskAvail = round($diskinfo['n_freespace']/1000,2);
            $diskUsed = round($diskSize - $diskAvail,2);
            $diskUsePercent = round($diskUsed/$diskSize,2)*100;
            $fpath = $rsUsing[0]['v_rcdiskpath4vpath'];
        }

        $recordStatus = $this->getIniStatus();
        $dd = date("Y-m-d",time());
        $where ="  D_StartTime >= '{$dd} 00:00:00' and D_StartTime <= '{$dd} 23:59:59'";
        $rec = M("rec_cdrinfo")->field("D_StartTime")->where($where)->order('D_StartTime desc')->find();
        $time = "";
        $recNum = 0;
        if($rec){
            $rs = M("rec_cdrinfo")->where($where)->field("count(N_SN) cnt")->find();
            $recNum = $rs['cnt'];
            $time = $rec['d_starttime'];
        }
        $rec = M("rec_bakinfo")->where($where)->field("D_StartTime")->order('D_StartTime desc')->find();
        if($rec){
            if($recNum == 0) $time = $rec['d_starttime'];
        }

        $total = $recNum;
        $recordInfo['lastTime'] = $time;
        $recordInfo['recordTotal'] = $total;
        $data['error'] = 0;
        $data['msg'] = '获取成功';
        $data['recordInfo'] = $recordInfo;
        $data['recordStatus'] = $recordStatus;
        $data['diskSize'] = $diskSize;
        $data['diskAvail'] = $diskAvail;
        $data['diskUsed'] = $diskUsed;
        $data['diskUsePercent'] = round($diskUsePercent,2);
        $data['fpath'] = $fpath;
        echo json_encode($data);exit;
    }

	//退出登录
	public function login_out(){
		session("uAccount",null);//用户ID
		session("uName",null);//用户账号
		session("uRights",null);//用户权限
		session("uLogTime",null);//登录时间
		session("uPrivilege",null);//有权设备
		session("uLogIP",null);//登录地址
		session("V_Ext",null);//有权分机
		session("V_SID",null);//有权工作站
		session("admininfo",null);
		$redirect ="/home/login/index";
		$this->success('退出成功', $redirect);
	}

	//验证码生成
	public function get_verify_png(){
		ob_clean();
		header("Content-type: image/png");
		$config =    array(
				'fontSize'    =>    50,    // 验证码字体大小
				'length'      =>    5,     // 验证码位数
				'useNoise'    =>    true, // 关闭验证码杂点
				'useCurve' => false,
				'fontttf' => '4.ttf',
				'imageW' => 0,
				'imageH' => 0
		);
		$Verify = new  Verify($config);
		$Verify->codeSet = '0123456789';
		$Verify->entry();
	}

	// 检测输入的验证码是否正确，$code为用户输入的验证码字符串
	public function check_verify($code, $id = ''){
		$verify = new  Verify();
		return $verify->check($code, $id);
	}

    public function uploadtest(){

       $this->assign("CurrentPage",'home');
        $this->display();
    }

	public function upload_translate(){
		$upload = new \Think\Upload();// 实例化上传类
	    $upload->maxSize   =     31457280 ;// 设置附件上传大小
	    $upload->exts      =     array('txt');// 设置附件上传类型
	    $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
	    $upload->savePath  =     ''; // 设置附件上传（子）目录
	    $upload->saveName = ''; //保持文件名不变
	    $upload->autoSub = true;
	    $upload->replace = true;
        $upload->subName = array('date','Ymd');
	    // 上传文件
	    $info   =   $upload->upload();
	    $returnData = array();
	    if(!$info) {// 上传错误提示错误信息
	        $returnData['msg'] = $upload->getError();
			$returnData['code'] =0;
	    }else{// 上传成功
	    	//获取文件内容
	       foreach($info as $file){
	    	 	$FilePath = $file['savepath'].$file['savename'];
           }
            $fileurl = './Uploads/'.$FilePath;
            if(file_exists($fileurl)){
               $houzhui = substr(strrchr($file['savename'], '.'), 1);
               $fileid = basename($file['savename'],".".$houzhui);
               $content = file_get_contents($fileurl);
               $content = trim($content);
               $rs = M("mgrid","cr_")->where("mgrid = '{$fileid}'")->save(array('contents'=>$content));
               if(false !== $rs){
                  $returnData['msg'] = "上传成功!";
			      $returnData['code'] =1;
               }
               else{
               	  $returnData['msg'] = "文件上传成功,翻译内容保存失败";
			      $returnData['code'] =0;
               }
            }
            else
            {
                $returnData['msg'] = "文件上传成功,翻译内容保存失败";
			    $returnData['code'] =0;
            }


	    }
	    $this->ajaxReturn($returnData);
	}

	//获取录音文件
	public function getRecordUrl(){
		$mgrid = $_REQUEST['mgrid'];
		if(empty($mgrid)){
		   $returnData['code'] =0;
           $returnData['msg'] = "参数不能为空";
		   $returnData['data'] ="";
		}
		$rs = M('mgrid','cr_')->where("mgrid = '{$mgrid}'")->find();

		if($rs){
			$returnData['msg'] = "获取成功";
		    $returnData['code'] = 1;
		    $returnData['data'] = host().$rs['fileurl'];
		}
		else{
			$returnData['msg'] = "录音文件不存在，获取失败";
		    $returnData['code'] = 0;
		    $returnData['data'] = "";
		}
		$this->ajaxReturn($returnData);
	}


	public function getfanyi(){
		$n_sn = $_REQUEST['n_sn'];
		if(empty($n_sn)){
		   $returnData['code'] =0;
           $returnData['msg'] = "参数不能为空";
		   $returnData['data'] ="";
		}
		$rs = M('mgrid','cr_')->where("N_SN = '{$n_sn}'")->find();

		if($rs){
			$returnData['msg'] = "获取成功";
		    $returnData['code'] = 1;
		    $returnData['data'] = $rs['contents'];
		}
		else{
			$returnData['msg'] = "翻译内容获取失败";
		    $returnData['code'] = 0;
		    $returnData['data'] = "";
		}
		$this->ajaxReturn($returnData);
	}

    public function getIniStatus(){
        header('content-type:text/html;charset=utf-8');
        //读取.init文件
        $config_file_path = 'C:\NeuTech\status\status.ini';
        //自己编写一个 my_parse_ini_file 将 db.init
        //说明 db.init 必须是规则
        //属性=属性值 可以多行
        $config_info = $this->parse_ini_file_multi($config_file_path,true);
        if(is_array($config_info)){
            foreach ($config_info as $k=>$v){
                $n = getCircfgByid($k);
                if($n){
                    $config_info[$k]['chname'] = $n['chname'];
                    $config_info[$k]['chnnel_no'] = $n['chno'];
                    $imgflag = 1;
                    if($v['recmode'] == 2){//压控
                        switch ($v['sigsta']){
                            case 1 :
                                $imgflag = 4;
                                break;
                            case 2 :
                                $imgflag = 1;
                                break;
                            case 4 :
                                $imgflag = 7;
                                break;
                            case 7 :
                                $imgflag = 3;
                                break;
                            case 11 :
                                $imgflag = 0;
                                break;
                            case 17 :
                                $imgflag = 4;
                                break;
                        }
                    }else{
                        switch ($v['vocsta']){
							case 160 :
                                if($v['sigsta'] == 1) $imgflag = 4;
                                break;
                            case 165 :
                                $imgflag = 3;
                                break;
                            case 166 :
                                $imgflag = 1;
                                break;
                        }
                    }
                    $config_info[$k]['imgflag'] = $imgflag;
                }
                else{
                    unset($config_info[$k]);
                }

            }
        }
		array_multisort(array_column($config_info,'chnnel_no'),SORT_ASC,$config_info);
        return json_encode($config_info);
    }

    function parse_ini_file_multi($file, $process_sections = false, $scanner_mode = INI_SCANNER_NORMAL){
        $explode_str = '.';
        $escape_char = "'";
        $data = parse_ini_file($file, $process_sections, $scanner_mode);
        if (!$process_sections) {
            $data = array($data);
        }
        if(isset($data['Globe'])) unset($data['Globe']);
        foreach ($data as $section_key => $section) {
            foreach($section as $key => $value){

                if(strpos($key, $explode_str)){
                    if(substr($key, 0, 1) !== $escape_char){
                        $sub_keys = explode($explode_str, $key);
                        $subs =& $data[$section_key];
                        echo "\r\n".'========='."\r\n";
                        print_r($subs);
                        print_r($data);
                        foreach($sub_keys as $sub_key){
                            if (!isset($subs[$sub_key])) {
                                $subs[$sub_key] = [];
                            }
                            $subs =& $subs[$sub_key];
                            echo "\r\n".'++++++++'."\r\n";
                            print_r($subs);
                            print_r($data);
                        }
                        $subs = $value;
                        echo "\r\n".'----------'."\r\n";
                        print_r($subs);
                        print_r($data);
                        unset($data[$section_key][$key]);
                    }else{
                        $new_key = trim($key, $escape_char);
                        $data[$section_key][$new_key] = $value;
                        unset($data[$section_key][$key]);
                    }
                }
            }
        }
        if (!$process_sections) {
            $data = $data[0];
        }
        return $data;
    }
}
